package nickname;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.Enumeration;
import javax.servlet.http.HttpServletRequest;
import org.apache.log4j.Logger;

public abstract class Utils {

	private static final Logger LOGGER = Logger.getLogger(Utils.class);

	@SuppressWarnings("unchecked")
	public static String request2NiceString(HttpServletRequest request) {
		
		Enumeration<String> parameterNames = request.getParameterNames();
		StringBuilder builder = new StringBuilder();
		while (parameterNames.hasMoreElements()) {
			String param = (String) parameterNames.nextElement();
			builder.append(param);
			builder.append("=");
			builder.append(request.getParameter(param));
			builder.append("; ");
		}
		
		return "Request from: " + request.getRemoteAddr() + ": " + "GET params: " + builder.toString(); 
	}
	
	public static String inputStream2String(InputStream inputStream) throws IOException{
		byte[] buffer = new byte[8192];
		int bytesRead;
		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
		
		while((bytesRead = inputStream.read(buffer)) != -1){
			outputStream.write(buffer, 0, bytesRead);
		}
		return outputStream.toString("US-ASCII");
	}
	
	public static boolean pingGgServer(InetAddress addr, int port, int timeout) {
		Socket socket = new Socket();
		Exception exception = null;
		try {
			socket.connect(new InetSocketAddress(addr, port), timeout);
			LOGGER.debug("Server " + addr + " - ONLINE");
		} catch (IOException e) {
			LOGGER.debug("Server " + addr + " " + "seems to be dead.");
			exception = e;
		}

		finally {
			try {
				socket.close();
			} catch (IOException e) {
			}
		}

		return exception == null ? true : false;
	}
}
